package com.jxauaia.contest.service.impl;

import com.jxauaia.contest.model.vo.CaptchaVO;
import com.jxauaia.contest.service.CaptchaService;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements CaptchaService {

    // 存储验证码的Map，key是captchaId，value是验证码内容
    private final Map<String, String> captchaStore = new ConcurrentHashMap<>();
    private final Random random = new Random();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    @Override
    public CaptchaVO generateCaptcha() {
        // 生成随机验证码
        String captchaCode = generateRandomCode();

        // 生成唯一ID
        String captchaId = UUID.randomUUID().toString();

        // 存储验证码
        captchaStore.put(captchaId, captchaCode);
        
        // 设置验证码5分钟后过期
        scheduleCaptchaExpiration(captchaId, 5);

        // 创建并返回CaptchaVO对象
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaId(captchaId);
        captchaVO.setCaptchaImage(generateCaptchaImage(captchaCode));
        
        return captchaVO;
    }

    @Override
    public boolean validate(String captchaId, String captchaCode) {
        if (captchaId == null || captchaCode == null) {
            return false;
        }

        String storedCode = captchaStore.get(captchaId);
        if (storedCode == null) {
            return false;
        }

        // 验证后移除验证码
        captchaStore.remove(captchaId);

        return storedCode.equalsIgnoreCase(captchaCode);
    }

    // 生成随机验证码
    private String generateRandomCode() {
        // 生成4位数字验证码
        return String.format("%04d", random.nextInt(10000));
    }
    
    // 设置验证码过期
    private void scheduleCaptchaExpiration(String captchaId, int minutes) {
        scheduler.schedule(() -> {
            captchaStore.remove(captchaId);
        }, minutes, TimeUnit.MINUTES);
    }

    // 生成验证码图片
    private String generateCaptchaImage(String code) {
        try {
            int width = 100;
            int height = 40;

            // 创建图像
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();

            // 设置背景色
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);

            // 绘制干扰线
            g.setColor(Color.LIGHT_GRAY);
            for (int i = 0; i < 20; i++) {
                int x1 = random.nextInt(width);
                int y1 = random.nextInt(height);
                int x2 = random.nextInt(width);
                int y2 = random.nextInt(height);
                g.drawLine(x1, y1, x2, y2);
            }

            // 设置字体
            g.setFont(new Font("Arial", Font.BOLD, 24));

            // 绘制验证码
            g.setColor(Color.BLUE);
            for (int i = 0; i < code.length(); i++) {
                g.drawString(String.valueOf(code.charAt(i)), 20 + i * 15, 25);
            }

            g.dispose();

            // 转换为Base64
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "png", baos);
            byte[] imageBytes = baos.toByteArray();

            return "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
            // 出错时返回简单文本
            return "data:image/png;base64,验证码生成失败";
        }
    }
}